﻿using System;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;

namespace AspNetCoreMini
{
    public class HttpListenerServer : IServer
    {
        private readonly HttpListener _httpListener;
        private readonly string[] _urls;

        public HttpListenerServer(params string[] urls)
        {
            _httpListener = new HttpListener();
            _urls = urls.Any() ? urls : new[] { "http://localhost:5000/" };
        }

        public async Task StartAsync(RequestDelegate handler)
        {
            Array.ForEach(_urls, url => _httpListener.Prefixes.Add(url));
            _httpListener.Start();

            Console.WriteLine("服务已经启动，主机地址：");
            foreach (var prefix in _httpListener.Prefixes)
            {
                Console.WriteLine(prefix);
            }

            while (true)
            {
                Handler(handler);
            }
        }

        private async Task Handler(RequestDelegate handler)
        {
            var listenerContext = await _httpListener.GetContextAsync();
            var feature = new HttpListenerFeature(listenerContext);
            var features = new FeatureCollection()
                .Set<IHttpRequest>(feature)
                .Set<IHttpResponse>(feature);
            var httpContext = new HttpContext(features);
            await handler(httpContext);
            listenerContext.Response.Close();
        }
    }
}